import Vue from 'vue'
import storage from 'good-storage'
import { BASEINFO } from '@/config'

let store = {}

export function SetStore(name, value) {
  store[name] = value
  storage.set(BASEINFO, store)
}

export function GetStore(name) {
  store = storage.get(BASEINFO) || {}
  return store[name]
}

export const Store = {
  dictionary: 'dictionary',
  user: 'user',
  roles: 'roles',
  enterprise: 'enterprise',
  organization: 'organization'
}

export const BUS = new Vue({})

export const EVENTS = {
  lawDisposalHidden: 'lawDisposalHidden',
  lawDisposalContent: 'lawDisposalContent',
  lawDetainHidden: 'lawDetainHidden',
  lawDetainContent: 'lawDetainContent',
  lawDetainList: 'lawDetainList',
  lawProgrammeContent: 'lawProgrammeContent',
  lawRecordContent: 'lawRecordContent',
  emergencyCommandActionAdd: 'emergencyCommandActionAdd',
  messageMettingPersonList: 'messageMettingPersonList'
}

export function IsRole(role) {
  let roles = GetStore(Store.roles)
  let obj = roles.find(v => v.name === role)
  return !!obj
}

export function JudgeRole() {
  const fn = function (context, role, callback) {
    if (IsRole(role)) {
      context.judgeSuccess = true
      context.judgeResult = typeof callback === 'function' ? callback() : callback
    }
    return context
  }
  return {
    judgeSuccess: false,
    judgeResult: null,
    administrator(callback, role = 'administrator') {
      return fn(this, role, callback)
    },
    government(callback, role = 'government') {
      return fn(this, role, callback)
    },
    enterprise(callback, role = 'enterprise') {
      return fn(this, role, callback)
    },
    assisstant(callback, role = 'assisstDept') {
      return fn(this, role, callback)
    },
    fail(callback) {
      if (!this.judgeSuccess) {
        callback()
      }
      return this
    },
    default(val) {
      return this.judgeSuccess ? this.judgeResult : val
    }
  }
}

export default {
  install(Vue) {
    Vue.prototype.$setStore = SetStore
    Vue.prototype.$getStore = GetStore
  }
}
